package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.entity.HazardReport;
import com.jhgsys.internal.hazard.service.IHazardReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @Author wanghw
 * @CreateTime 2024/8/21 15:59
 * @Description 隐患整改签发
 * @Version 1.0
 */
@Slf4j
@Validated
@Controller
public class hazardReportIssuanceController extends BaseController {
    @Autowired
    private IHazardReportService hazardReportService;



    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportIssuance")
    @RequiresPermissions("hazardReportIssuance:view")
    public String hazardReportIssuanceIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportIssuance/hazardReportIssuanceList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportIssuance/issuance/{id}")
    @RequiresPermissions("hazardReportIssuance:issuance")
    public String hazardReportUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportIssuance/hazardReportIssuanceEdit");
    }

    /**
     * 隐患待签发（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReportIssuance/list")
    @ResponseBody
    @RequiresPermissions("hazardReportIssuance:view")
    public FebsResponse hazardReportList(QueryRequest request, HazardReportDto hazardReport) {
        hazardReport.setStatus(HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE);
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 整改签发
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("整改签发")
    @PostMapping("hazardReportIssuance")
    @ResponseBody
    @RequiresPermissions("hazardReportIssuance:issuance")
    public FebsResponse submitHazardReportRectification(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        checkParams(hazardReport);
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待签发的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.WAITING_ISSUANCE.equals(report.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经签发过！");
            }
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            hazardReport.setIssuanceDate(new Date());
            hazardReport.setIssuanceUserId(getCurrentUser().getUserId());
            hazardReport.setIssuanceRealName(getCurrentUser().getUname());
            hazardReport.setStatus(HazardConstant.HAZARD_STATUS.ISSUANCED);
            this.hazardReportService.saveHazardReportAppealRecord(hazardReport);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "签发隐患信息失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    private void checkParams( HazardReportDto hazardReport) throws FebsException {
        if(StringUtils.isBlank(hazardReport.getReportId())){
            throw new FebsException("隐患报告ID不能为空");
        }

    }


}
